package com.competition.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.competition.entity.HotNews;
import com.competition.mapper.HotNewsMapper;
import com.competition.resp.ResponseResult;
import com.competition.service.HotNewsService;
import com.upyun.UpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/hotnews")
public class HotNewsController {

    @Autowired
    private HotNewsMapper hotNewsMapper;
    @Autowired
    private HotNewsService hotNewsService;
    @Autowired
    CommonController commonController;

    @Value("${yCatalogue}")
    private String yCatalogue;

    private String basePath = "hot-news";

    @GetMapping("/getNews")
    public ResponseResult getNews(@RequestParam("current")int current){
        if (current < 0){
            return  new ResponseResult(300,"参数异常",null);
        }
        Page<HotNews> page = new Page<>(current,5);//页码（current），每页显示的条数（size）
        Page<HotNews> list = null;
        try {
            list = hotNewsMapper.selectPage(page,null);
            if (list.hasNext()){
                return  new ResponseResult(200,"获取成功",list);
            }else {
                return new ResponseResult(200,"最后一页",list);
            }
        } catch (Exception e) {
            return  new ResponseResult(300,"获取失败",null);
        }


    }
    @GetMapping("/getNewsById")
    public ResponseResult getNewsById(@RequestParam("newId")String newId){
        if (newId == null){
            return new ResponseResult(300,"空值",null);
        }
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("hot_news_id",newId);
            HotNews one = hotNewsService.getOne(queryWrapper);
            return new ResponseResult(200,"获取成功",one);
        } catch (Exception e) {
            return new ResponseResult(300,"获取失败",null);
        }
    }


    @GetMapping("/queryHotNewsList")
    public ResponseResult<Object> queryHotNewsList(@RequestParam HashMap<String,Object> params) {
        if(params.get("page")==null||params.get("pageSize")==null){
            return new ResponseResult<Object>(400,"参数错误",null);
        }
        QueryWrapper<HotNews> objectQueryWrapper = new QueryWrapper<>();
        int page = Integer.parseInt(params.get("page").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        if(params.get("hotNewsTitle")!=null){
            objectQueryWrapper.like("hot_news_title",params.get("hotNewsTitle").toString());
        }
        objectQueryWrapper.last("limit "+pageSize+" offset "+(page - 1) * pageSize);
        List<HotNews> hotNewsList = hotNewsService.list(objectQueryWrapper);
        HashMap<String, Object> resMap = new HashMap<>();
        long count = hotNewsService.count();
        resMap.put("total",count);
        resMap.put("hotNewsList",hotNewsList);
        return new ResponseResult<Object>(200,"获取新闻列表成功",resMap);
    }


    @GetMapping("/queryHotNewsById")
    public ResponseResult<Object> queryHotNewsById(@RequestParam HashMap<String,Object> params) {
        if(params.get("hotNewsId")==null){
            return new ResponseResult<Object>(400,"参数错误",null);
        }
        QueryWrapper<HotNews> hotNewsQueryWrapper = new QueryWrapper<>();
        hotNewsQueryWrapper.eq("hot_news_id",params.get("hotNewsId").toString());
        HotNews hotNews = hotNewsService.getOne(hotNewsQueryWrapper);
        if(hotNews==null){
            return new ResponseResult<Object>(400,"新闻不存在",null);
        }
        return new ResponseResult<Object>(200,"获取新闻成功",hotNews);
    }

    @DeleteMapping("/deleteHotNewsById")
    @Transactional
    public ResponseResult<Object> deleteHotNewsById(@RequestParam HashMap<String,Object> params) {
        if(params.get("hotNewsId")==null){
            return new ResponseResult<Object>(400,"参数错误",null);
        }
        //删除之前云服务的照片
        HotNews oldHotNews = hotNewsService.getOne(new QueryWrapper<HotNews>().eq("hot_news_id", params.get("hotNewsId")));
        QueryWrapper<HotNews> hotNewsQueryWrapper = new QueryWrapper<>();
        hotNewsQueryWrapper.eq("hot_news_id", params.get("hotNewsId").toString());
        // 删除商品信息
        hotNewsService.remove(hotNewsQueryWrapper);
        if(oldHotNews.getHotNewsImg()!=null && !oldHotNews.getHotNewsImg().equals("")){
            String[] strings = oldHotNews.getHotNewsImg().split(basePath);
            ResponseResult responseResult = commonController.deleteImg(this.basePath, strings[1]);
            if(responseResult.getCode()!=200){
                TransactionAspectSupport.currentTransactionStatus()
                        .setRollbackOnly();
                return new ResponseResult<Object>(500,"删除新闻照片失败",null);
            }
        }

        return new ResponseResult<Object>(200,"删除商品成功",null);
    }

    @PostMapping("/addHotNews")
    public ResponseResult<Object> addHotNews(HotNews hotNews,@RequestPart(value = "file",required = false) MultipartFile file) throws UpException, IOException {
        hotNews.setHotNewsImg(null);
        if(file != null){
            String filename = file.getOriginalFilename();
            assert filename != null;
            int dotIndex = filename.lastIndexOf('.');
            String suffix = filename.substring(dotIndex + 1);
            ResponseResult responseResult = commonController.uploadImg(file, basePath, suffix);
            if(responseResult.getCode()!=200){
                return new ResponseResult<Object>(500,"文件上传失败");
            }
            hotNews.setHotNewsImg("https://img.cjz.red/"+this.yCatalogue + "/"+basePath+"/" + responseResult.getData().toString());
        }
        UUID uuid = UUID.randomUUID();
        hotNews.setHotNewsCount(0);
        hotNews.setHotNewsId(uuid.toString());
        hotNewsService.save(hotNews);
        return new ResponseResult<Object>(200,"添加商品成功",null);
    }

    @PutMapping("/modifyHotNews")
    public ResponseResult<Object> modifyHotNews(HotNews hotNews,@RequestPart(value = "file",required = false) MultipartFile file) throws UpException, IOException {
        if(hotNews.getHotNewsId() == null){
            return new ResponseResult<Object>(400,"参数错误",null);
        }
        hotNews.setHotNewsImg(null);
        if(file != null){
            String filename = file.getOriginalFilename();
            assert filename != null;
            int dotIndex = filename.lastIndexOf('.');
            String suffix = filename.substring(dotIndex + 1);
            ResponseResult responseResult = commonController.uploadImg(file, basePath, suffix);
            if(responseResult.getCode()!=200){
                return new ResponseResult<Object>(500,"文件上传失败");
            }
            hotNews.setHotNewsImg("https://img.cjz.red/"+this.yCatalogue + "/"+basePath+"/" + responseResult.getData().toString());
            //删除之前云服务的照片
            HotNews oldHotNews = hotNewsService.getOne(new QueryWrapper<HotNews>().eq("hot_news_id", hotNews.getHotNewsId()));
            if(oldHotNews.getHotNewsImg()!=null && !oldHotNews.getHotNewsImg().equals("")){
                String[] strings = oldHotNews.getHotNewsImg().split(basePath);
                commonController.deleteImg(basePath, strings[1]);
            }

        }
        UpdateWrapper<HotNews> hotNewsUpdateWrapper = new UpdateWrapper<>();
        hotNewsUpdateWrapper.eq("hot_news_id", hotNews.getHotNewsId());
        hotNewsService.update(hotNews,hotNewsUpdateWrapper);
        return new ResponseResult<Object>(200,"修改商品成功",null);
    }


    @GetMapping("/queryHotNewsListByCountTop")
    public ResponseResult<Object> queryAgriculturalTrainingListByCountTop(Integer top){
        if (top == null || top <= 0){
            return  new ResponseResult<Object>(400,"参数错误");
        }
        QueryWrapper<HotNews> hotNewsQueryWrapper = new QueryWrapper<>();
        hotNewsQueryWrapper.orderByDesc("hot_news_count");
        hotNewsQueryWrapper.last("limit " + top);
        List<HotNews> list = hotNewsService.list(hotNewsQueryWrapper);
        return new ResponseResult<Object>(200,"查询成功",list);
    }

}
